import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import {
  Card,
  message,
  Tooltip,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Modal,
  Descriptions,
  Spin,
  Divider,
  Popconfirm,
} from 'antd';
import OrderService from '@/services/order';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import CopyToClipboard from '@/components/CopyToClipboard';
import { getTimeDistance } from '@/utils/utils';
import moment from 'moment';
import { getParam } from '@/utils/utils.js';
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

import { router } from 'umi';
@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/userOrderPurchase'],
}))
@Form.create()
export default class Purchase extends Component {
  state = {
    current: 1,
    visible: false,
    orderId: null,
    datas: {},
    yunTime: getTimeDistance('month'),
    deliverOptions: [],
    title: '备注',
  };
  componentDidMount() {
    this.onList(1, 10, {
      state: 'WAITING_FOR_DELIVERY'
    });
    this.getExpressList();
    this.props.dispatch({
      type: 'order/PlateformChannel',
    });
  }
  getExpressList = () => {
    OrderService.selectExpressList().then(res => {
      this.setState({
        deliverOptions: res || [],
      });
    });
  };
  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/userOrderPurchase',
      payload: {
        pageSize,
        pageNumber,
        // status: getParam('status') || '',
        ...data,
      },
    });
  };
  handleSubmit = e => {
    e && e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      if (values.createDate && values.createDate.length < 1) {
        values.createTimeStart = '';
        values.createTimeEnd = '';
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      } else if (values.createDate) {
        values.createTimeStart = moment(values.createDate[0]).format('YYYY-MM-DD HH:mm:ss');
        values.createTimeEnd = moment(values.createDate[1]).format('YYYY-MM-DD HH:mm:ss');
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      } else {
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      }
    });
  };
  // 重置
  handleReset = e => {
    this.props.form.resetFields();
    this.props.form.setFieldsValue({
      state: undefined,
    });
    this.handleSubmit(e);
  };
  showModal = (orderId, title) => {
    this.setState({
      visible: true,
      orderId,
      title,
    });
  };

  handleOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dispatch } = this.props;

        if (this.state.title === '发货') {
          dispatch({
            type: 'order/purchaseOrderDelivery',
            payload: {
              orderId: this.state.orderId,
              expressId: values.expressId,
              expressNo: values.expressNo,
            },
            callback: res => {
              this.setState({
                visible: false,
              });
              this.handleSubmit();
              // this.onList(1, 10);
            },
          });
        } else if (this.state.title === '修改物流信息') {
          dispatch({
            type: 'order/purchaseOrderDelivery',
            payload: {
              orderId: this.state.orderId,
              expressId: values.expressId,
              expressNo: values.expressNo,
            },
            callback: res => {
              this.setState({
                visible: false,
              });
              this.handleSubmit();
              // this.onList(1, 10);
            },
          });
        } else {
          dispatch({
            type: 'order/orderRemark',
            payload: {
              orderId: this.state.orderId,
              remark: values.beizhu,
              orderType: '01',
            },
            callback: res => {
              this.setState({
                visible: false,
              });
            },
          });
        }
      }
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };
  //table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current,
      },
      () => {
        const params = {
          state: 'WAITING_FOR_DELIVERY',
          ...this.state.datas,
        }
        this.onList(e.current, 10, params);
      },
    );
  };
  onexport = () => {
    const { yunTime } = this.state;
    if (this.props.form.getFieldValue('createDate')) {
      this.props.dispatch({
        type: 'order/purchaseOrderExport',
        payload: {
          createTimeEnd: moment(this.props.form.getFieldValue('createDate')[1]).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
          createTimeStart: moment(this.props.form.getFieldValue('createDate')[0]).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
        },
      });
    } else {
      this.props.dispatch({
        type: 'order/purchaseOrderExport',
        payload: {
          createTimeEnd: moment(yunTime[1]).format('YYYY-MM-DD HH:mm:ss'),
          createTimeStart: moment(yunTime[0]).format('YYYY-MM-DD HH:mm:ss'),
        },
      });
    }
  };
  confirm = e => {
    this.props.dispatch({
      type: 'order/purchaseOrder',
      payload: {
        orderId: e,
      },
      callback: res => {
        this.onList(this.state.current, 10, this.state.datas);
      },
    });
  };
  render() {
    const { userOrderPurchaseList, userOrderPurchaseTotal, loading, PlateformList } = this.props;
    const { deliverOptions } = this.state;
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: userOrderPurchaseTotal,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      ),
    };
    let detailsStute = {
      WAITING_FOR_PAY: '待支付',
      CANCEL: '已取消',
      WAITING_FOR_DELIVERY: '待发货',
      WAITING_RECEIVE: '待收货',
      FINISH: '已完成',
    };
    const columns = [
      {
        title: '订单编号',
        dataIndex: 'orderId',
        width: '10%',
        render: orderId => <CopyToClipboard text={orderId} />,
      },
      {
        title: '渠道来源',
        dataIndex: 'channelName',
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: '10%',
        render: productName => {
          return (
            <>
              <Tooltip placement="top" title={productName}>
                <div
                  style={{
                    width: 60,
                    /* overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap', */
                  }}
                >
                  {productName}
                </div>
              </Tooltip>
            </>
          );
        },
      },
      {
        title: '总金额',
        width: '10%',
        render: e => {
          return <>{e.totalAmount}</>;
        },
      },
      {
        title: '下单人姓名',
        width: '10%',
        render: e => {
          return (
            <>
              {e.userName}
            </>
          );
        },
      },
      {
        title: '手机号',
        width: '10%',
        render: e => {
          return (
            <>
              {e.telephone}
            </>
          );
        },
      },
      {
        title: '下单时间',
        dataIndex: 'createTime',
        width: '15%',
      },
      {
        title: '订单状态',
        dataIndex: 'state',
        width: '10%',
        // render: status => {
        //   return (
        //     <>
        //       <div style={{ color: '#FA8C16' }}>待支付</div>
        //       <div style={{ color: '#52C41A' }}>待商家发货</div>
        //       <div style={{ color: '#000000' }}>租用中</div>
        //       <div style={{ color: '#000000' }}>支付中</div>
        //       <div style={{ color: '#F5222D' }}>订单关闭</div>
        //       <div style={{ color: '#FA8C16' }}>待用户确认收货</div>
        //       <div style={{ color: '#FA8C16' }}>待结算</div>
        //       <div style={{ color: '#F5222D' }}>已逾期</div>
        //       <div style={{ color: '#000000' }}>已完成</div>
        //     </>
        //   );
        // },
        render: state => {
          return <span>{detailsStute[state]}</span>;
        },
      },
      {
        title: '操作',
        width: '180px',
        fixed: 'right',
        align: 'center',
        render: e => {
          return (
            <>
              <div>
                <a
                  style={{ cursor: 'pointer' }}
                  // onClick={() => router.push(`/Order/PurchaseDetails?id=${e.orderId}`)}
                  href={`#/Order/Purchase/PurchaseDetails?id=${e.orderId}`}
                  target="_blank"
                >
                  详情
                </a>
                <Divider type="vertical" />
                <a style={{ cursor: 'pointer' }} onClick={() => this.showModal(e.orderId, '备注')}>
                  备注
                </a>
              </div>
              <div>
                {(e && e.state === 'WAITING_FOR_PAY') ||
                (e && e.state === 'WAITING_FOR_DELIVERY') ? (
                  <Popconfirm
                    placement="top"
                    title={'确定要关闭订单并退款吗？'}
                    onConfirm={() => this.confirm(e.orderId)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button type="link">关闭订单</Button>
                  </Popconfirm>
                ) : null}
              </div>
              {e && e.state === 'WAITING_FOR_DELIVERY' ? (
                <span
                  style={{ cursor: 'pointer', color: '#E83F40' }}
                  onClick={() => this.showModal(e.orderId, '发货')}
                >
                  发货
                </span>
              ) : null}
              {e && e.state === 'WAITING_RECEIVE' ? (
                <span
                  style={{ cursor: 'pointer', color: '#E83F40' }}
                  onClick={() => this.showModal(e.orderId, '修改物流信息')}
                >
                  修改物流信息
                </span>
              ) : null}
            </>
          );
        },
      },
    ];
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <Form.Item label="商品名称">
              {getFieldDecorator('productName', {})(<Input allowClear placeholder="请输入商品名称" />)}
            </Form.Item>
            <Form.Item label="下单人姓名">
              {getFieldDecorator('userName', {})(<Input allowClear placeholder="请输入下单人姓名" />)}
            </Form.Item>
            <Form.Item label="下单人手机号">
              {getFieldDecorator('telephone', {})(<Input allowClear placeholder="请输入下单人手机号" />)}
            </Form.Item>
            <Form.Item label="订单编号">
              {getFieldDecorator('orderId', {})(<Input allowClear placeholder="请输入订单编号" />)}
            </Form.Item>
            <Form.Item label="创建时间">
              {getFieldDecorator(
                'createDate',
                {},
              )(<RangePicker allowClear placeholder={['下单开始时间', '下单结束时间']} />)}
            </Form.Item>
            <Form.Item label="订单状态">
              {getFieldDecorator(
                'state',
                {
                  initialValue: "WAITING_FOR_DELIVERY",
                },
              )(
                <Select placeholder="订单状态" allowClear style={{ width: 180 }}>
                  <Option value="WAITING_FOR_PAY">待支付</Option>
                  <Option value="CANCEL">已取消</Option>
                  <Option value="WAITING_FOR_DELIVERY">待发货</Option>
                  <Option value="WAITING_RECEIVE">待收货</Option>
                  <Option value="FINISH">已完成</Option>
                </Select>,
              )}
            </Form.Item>
            <div>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="button" onClick={this.handleReset}>
                  重置
                </Button>
              </Form.Item>
              <Form.Item>
                <Button onClick={this.onexport}>导出</Button>
              </Form.Item>
            </div>
          </Form>
          <Spin spinning={loading}>
            <MyPageTable
              scroll
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={onTableData(userOrderPurchaseList)}
              columns={columns}
            />
          </Spin>
        </Card>

        <Modal
          title={this.state.title}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose
        >
          <Form>
            {this.state.title === '备注' ? (
              <Form.Item label="备注内容" {...formItemLayout}>
                {getFieldDecorator('beizhu', {
                  rules: [{ required: true, message: '请输入备注' }],
                })(<TextArea placeholder="请输入" />)}
              </Form.Item>
            ) : null}

            {this.state.title === '发货' ? (
              <>
                <Form.Item>
                  {getFieldDecorator(
                    'expressId',
                    {},
                  )(
                    <Select style={{ width: '100%' }} placeholder="请选择物流公司">
                      {deliverOptions.map(option => {
                        return (
                          <Option key={option.id} value={option.id}>
                            {option.name}
                          </Option>
                        );
                      })}
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('expressNo', {})(<Input placeholder="请输入物流单号" />)}
                </Form.Item>
              </>
            ) : null}
            {this.state.title === '修改物流信息' ? (
              <>
                <Form.Item>
                  {getFieldDecorator(
                    'expressId',
                    {},
                  )(
                    <Select style={{ width: '100%' }} placeholder="请选择物流公司">
                      {deliverOptions.map(option => {
                        return (
                          <Option key={option.id} value={option.id}>
                            {option.name}
                          </Option>
                        );
                      })}
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('expressNo', {})(<Input placeholder="请输入物流单号" />)}
                </Form.Item>
              </>
            ) : null}
          </Form>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
